package com.zhenai.rocyuan.commons.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.zhenai.rocyuan.modules.myannotation.d1.Default;
import com.zhenai.rocyuan.modules.myannotation.d1.Game;



/**
 * 
 * @author zhza1129
 *
 */
public class AnnontationUtils {

	public static <T extends Annotation> T getFromMethed(Class<T> annotationClazz, Object o,
			String methodName) {
		if (o == null) {
			return null;
		}
		Class<? extends Object> objectClass = o.getClass();
		try {
			Method method = objectClass.getDeclaredMethod(methodName);
			return method.getAnnotation(annotationClazz);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		}
	}

	public static <T extends Annotation> T getFromMethedOrType(Class<T> annotationClazz, Object o,
			String methodName) {
		if (o == null) {
			return null;
		}
		Class<? extends Object> objectClass = o.getClass();
		T annotation;
		try {
			Method method = objectClass.getDeclaredMethod(methodName);
			annotation = method.getAnnotation(annotationClazz);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		}
		if (annotation != null) {
			return annotation;
		}
		return objectClass.getAnnotation(annotationClazz);
	}

	/**
	 * 
	 * @param annotationClass
	 * @param objClass
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isAnnotationPresent(Class<? extends Annotation> annotationClass ,Class objClass){
		if(objClass.isAnnotationPresent(annotationClass)){
			return true;
		}
		Method [] allMethods = objClass.getDeclaredMethods();
		for( Method method : allMethods ){
			if(method.isAnnotationPresent(annotationClass)){
				return true;
			}
		}
		
		Field[] allFields = objClass.getDeclaredFields();
		for(Field field : allFields){
			if(field.isAnnotationPresent(annotationClass)){
				return true;
			}
		}
		
		return false;
	}
	

	public static void main(String[] args) {
		System.out.println(isAnnotationPresent(Default.class, Game.class));
	}
	
}
